package com.csqf.booksys.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.csqf.booksys.entity.Admins;
import com.csqf.booksys.service.IAdminsService;
import com.csqf.booksys.service.impl.AdminsServiceImpl;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    IAdminsService adminService = new AdminsServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//
		String action = request.getParameter("action");
		if("login".equals(action)){
			login(request,response);
		}else if("exit".equals(action)){
			exit(request,response);
		}
	}

	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	     //1、获取数据
		 String msg = null;
		 String name = request.getParameter("name");
		 String password = request.getParameter("password");
		 //2、调用业务层方法处理数据
		 Admins admin = adminService.find(name, password);
		 if(admin != null){
			 //登录成功
			 HttpSession session = request.getSession();
			 session.setAttribute("loginedInfo", admin);
			 //
			 Cookie ck = new Cookie("JSESSIONID",session.getId());
			 ck.setMaxAge(24*60*60);
			 response.addCookie(ck);
			 //
			 response.sendRedirect(request.getContextPath()+"/book?action=all");
		 }else{
			//登录失败
			 msg = "账户或密码错误，请重新登录！";
			 request.setAttribute("msg", msg);
			 request.getRequestDispatcher("/login.jsp").forward(request, response);
		 }
	}
	
	protected void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	     //1、获取session对象
		  HttpSession session = request.getSession(false);
		  if(session != null){
			  session.removeAttribute("loginedInfo");
			  response.sendRedirect(request.getContextPath()+"/login.jsp");
		  }else{
			  response.sendRedirect(request.getContextPath()+"/login.jsp");
		  }
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
